package com.chinawlx.wlxteacher.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXCourseManageBean;
import com.chinawlx.wlxteacher.ui.activity.WLXClazzRoomDetailActivity;
import com.chinawlx.wlxteacher.ui.adapter.CourseManageAdapter;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXNetUtil;
import com.chinawlx.wlxteacher.utils.WLXTeacherConstant;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_schedule;
import com.chinawlx.wlxteacher.wlx_scheduleDao;
import com.chinawlx.wlxteacher.wlx_student_study;
import com.chinawlx.wlxteacher.wlx_student_studyDao;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.refreshlayout.BGAMeiTuanRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import rx.Subscriber;

/**
 * 课程管理界面
 * <p>
 * Created by yyc on 2016/8/2.
 */
public class WLXCourseManageFragment extends WLXBaseFragment implements BGARefreshLayout
        .BGARefreshLayoutDelegate {
    private int paging_index = 1;//分页索引
    private int paging_size = 10;//每页大小
    private boolean mHasMoreData = true;

    @BindView(R.id.rl_modulename_refresh)
    BGARefreshLayout mRefreshLayout;
    @BindView(R.id.rl_container_empty)
    RelativeLayout mRlContainerEmpty;
    @BindView(R.id.tv_msg)
    TextView mTvMsg;

    @BindView(R.id.lv_course_manage)
    ListView courseManageListView;

    private String grade_id;
    private List<wlx_schedule> scheduleList;
    private long currentTimestamp = System.currentTimeMillis() / 1000L; //当前时间的时间戳
    private WLXLoadingFragment wlxLoadingFragment;
    private CourseManageAdapter courseManageAdapter;
    private List<wlx_schedule> scheduleList1;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_course_manage, null);
        ButterKnife.bind(this, view);

        init();
        return view;
    }

    private void init() {
        initView();
//        initData();
    }

    private void initView() {
        grade_id = getArguments().getString(WLXTeacherConstant.GRADE_ID);
        initAdapter();
        initRefreshLayout();
    }

    @Override
    public void onResume() {
        super.onResume();
        mRefreshLayout.beginRefreshing();
        courseManageAdapter.notifyDataSetChanged();
    }

    private void initAdapter() {
        courseManageAdapter = new CourseManageAdapter(mContext,grade_id);
        courseManageListView.setAdapter(courseManageAdapter);
        courseManageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String schedule_id = scheduleList.get(position).getSchedule_id();
                wlx_schedule wlxSchedule = (wlx_schedule) courseManageAdapter.getItem(position);
                String schedule_id = wlxSchedule.getSchedule_id();
                TextView btnText = (TextView) view.findViewById(R.id.tv_satus_btn);
                WLXLogUtil.printE("``````````btnText----------:" + "-----" + btnText.getText());
                Bundle bundle = new Bundle();
                bundle.putString(WLXTeacherConstant.GRADE_ID, grade_id);
                bundle.putString(WLXTeacherConstant.SCHEDULE_ID, schedule_id);
                startActivity(WLXClazzRoomDetailActivity.class, false, bundle);
            }
        });
    }

    //--------刷新内容 start---------

    private void initRefreshLayout() {
        mRefreshLayout.setDelegate(this);
        BGAMeiTuanRefreshViewHolder meiTuanRefreshViewHolder = new BGAMeiTuanRefreshViewHolder
                (this.getContext(), true);
        meiTuanRefreshViewHolder.setPullDownImageResource(R.drawable.yuanq);
        meiTuanRefreshViewHolder.setChangeToReleaseRefreshAnimResId(R.drawable
                .bga_refresh_mt_change_to_release_refresh);
        meiTuanRefreshViewHolder.setRefreshingAnimResId(R.drawable.bga_refresh_mt_refreshing);

        mRefreshLayout.setRefreshViewHolder(meiTuanRefreshViewHolder);
        mRefreshLayout.beginRefreshing();
    }

    //开始刷新
    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.CheckNetwork(mContext)) {
            paging_index = 1;
            requestDataFromNet();
        } else {//无网络
            mRefreshLayout.endRefreshing();
            initDataFromDataBase();
        }
    }


    //处理上拉加载,在这里上拉加载更多,
    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.CheckNetwork(getActivity())) {
            if (mHasMoreData) {
                paging_index++;
                requestDataFromNet();
                return true;
            } else {
                WLXCustomToast.show("没有更多数据");
                return false;
            }
        } else {
//            WLXCustomToast.show("无网络!");
            initDataFromDataBase();
            return false;
        }
    }

    //-----------刷新 end------

    private void requestDataFromNet() {
        wlxLoadingFragment = WLXLoadingFragment.getInstance();
        wlxLoadingFragment.show(getActivity().getSupportFragmentManager(), "");
        WLXHttpRxHelper.getInstance().getCourseManage(grade_id, paging_index + "", paging_size +
                "", new
                Subscriber<WLXCourseManageBean>() {


                    @Override
                    public void onCompleted() {
                        initDataFromDataBase();
                        wlxLoadingFragment.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }

                    @Override
                    public void onNext(WLXCourseManageBean wlxCourseManageBean) {

                        saveScheduleTable(wlxCourseManageBean);
                        saveStudentStudyList(wlxCourseManageBean);
                    }
                });
    }


    /**
     * 存储 wlx_student_study 表单
     *
     * @param wlxCourseManageBean
     */
    private void saveStudentStudyList(WLXCourseManageBean wlxCourseManageBean) {
        List<WLXCourseManageBean.DataBean.StudentStudyListBean> student_study_list =
                wlxCourseManageBean.getData().getStudent_study_list();
        Gson gson = new Gson();
        for (WLXCourseManageBean.DataBean.StudentStudyListBean studyListBean :
                student_study_list) {
            String student_study_id = Integer.toString(studyListBean.getId());
            int student_id = studyListBean.getStudent_id();
            int teacher_user_id = studyListBean.getTeacher_user_id();
            int grade_id = studyListBean.getGrade_id();
            int schedule_id = studyListBean.getSchedule_id();
            String student_remark = studyListBean.getStudent_remark();
            String teacher_remark = studyListBean.getTeacher_remark();
            String study_status_code = studyListBean.getStudy_status().getKey();
            String extend_info = gson.toJson(studyListBean.getExtend());
            long start_date = WLXDateUtil.getStringToDate(studyListBean.getStart_date());
            long end_date = WLXDateUtil.getStringToDate(studyListBean.getEnd_date());
            long last_modified_date = WLXDateUtil.getStringToDate(studyListBean
                    .getLast_modified_date());
            int version = studyListBean.getVersion();
            wlx_student_study wlx_student_study = new wlx_student_study(student_study_id,
                    student_id, teacher_user_id, grade_id,
                    schedule_id, student_remark, teacher_remark, study_status_code, extend_info,
                    start_date, end_date, last_modified_date, version);
            List<com.chinawlx.wlxteacher.wlx_student_study> wlxStudentStudy = WLXGreenDaoUtil
                    .getStudentStudyDao().queryBuilder().where(wlx_student_studyDao
                            .Properties.Student_study_id.eq(student_study_id)).list();
            if (wlxStudentStudy.size() > 0) {
                if (last_modified_date > wlx_student_study.getLast_modified_date()) {
                    WLXGreenDaoUtil.getStudentStudyDao().update(wlx_student_study);
                }
            } else {
                WLXGreenDaoUtil.getStudentStudyDao().insert(wlx_student_study);
            }
        }
    }

    /**
     * 存储 wlx_schedule 表单
     *
     * @param wlxCourseManageBean
     */
    private void saveScheduleTable(WLXCourseManageBean wlxCourseManageBean) {
        List<WLXCourseManageBean.DataBean.ScheduleListBean> schedule_list =
                wlxCourseManageBean.getData().getSchedule_list();
        for (WLXCourseManageBean.DataBean.ScheduleListBean scheduleListBean :
                schedule_list) {
            String schedule_id = Integer.toString(scheduleListBean.getId());
            int teacher_user_id = scheduleListBean.getUser_id();
            int org_user_id = scheduleListBean.getOrg_user_id();
            int addition_id = scheduleListBean.getAddition_id();
            String addition_student_ids = scheduleListBean
                    .getAddition_student_ids();
            int space_id = scheduleListBean.getSpace_id();
            int classroom_id = scheduleListBean.getClassroom_id();
            int grade_id = scheduleListBean.getGrade_id();
            String grade_title = scheduleListBean.getGrade_title();
            int score_well = scheduleListBean.getScore_well();
            int score_good = scheduleListBean.getScore_good();
            int score_bad = scheduleListBean.getScore_bad();
            String prepare_content = scheduleListBean.getPrepare_content();
            String remark = scheduleListBean.getRemark();
            String class_type_code = scheduleListBean.getClass_type().getCode();
            String class_child_type_code = scheduleListBean.getClass_child_type()
                    .getCode();
            String grade_type_code = scheduleListBean.getGrade_type().getKey();
            int is_study = scheduleListBean.isIs_study() == true ? 1 : 0;
            int is_homework = scheduleListBean.isIs_homework() == true ? 1 : 0;
            int is_addition = scheduleListBean.isIs_addition() == true ? 1 : 0;
            int is_finished = scheduleListBean.isIs_finished() == true ? 1 : 0;
            String extend_info = new Gson().toJson(scheduleListBean.getExtend());

            long opening_date = WLXDateUtil.getStringToDate(scheduleListBean
                    .getOpening_date());
            WLXLogUtil.printI(scheduleListBean.getOpening_date());
            long closing_date = WLXDateUtil.getStringToDate(scheduleListBean
                    .getClosing_date());
            long schedule_date = WLXDateUtil.getStringToDate(scheduleListBean
                    .getSchedule_date());
            long last_modified_date = WLXDateUtil.getStringToDate(scheduleListBean
                    .getLast_modified_date());
            wlx_schedule wlxSchedule = new wlx_schedule(schedule_id,
                    teacher_user_id, org_user_id,
                    addition_id, addition_student_ids, space_id, classroom_id,
                    grade_id, grade_title, score_well, score_good, score_bad,
                    prepare_content, remark, class_type_code,
                    class_child_type_code, grade_type_code, is_study,
                    is_homework, is_addition, is_finished, extend_info,
                    opening_date, closing_date, schedule_date, last_modified_date);

            List<wlx_schedule> wlx_schedules = WLXGreenDaoUtil
                    .getScheduleDao().queryBuilder().where(wlx_scheduleDao
                            .Properties.Schedule_id.eq(schedule_id)).list();
            if (wlx_schedules.size() > 0) {
                Long saveData = wlx_schedules.get(0).getLast_modified_date();
                WLXLogUtil.printE("数据库时间: "+saveData+"服务器时间: "+last_modified_date);
                if (last_modified_date > wlx_schedules.get(0)
                        .getLast_modified_date()) {
                    WLXGreenDaoUtil.getScheduleDao().update(wlxSchedule);
                }
            } else {
                WLXGreenDaoUtil.getScheduleDao().insert(wlxSchedule);
            }
        }
    }

    private void initDataFromDataBase() {
        List<wlx_schedule> scheduleAllList = WLXGreenDaoUtil.getScheduleDao().queryBuilder().list();
        if (scheduleAllList != null) {
            //所有数据
//            scheduleList = WLXGreenDaoUtil.getScheduleDao().queryBuilder().where
//                    (wlx_scheduleDao.Properties.Grade_id.eq(grade_id)).orderAsc(wlx_scheduleDao
//                    .Properties.Opening_date).list();
            // TODO: 16/9/29 注释以下代码,方便查看出勤率,勿删!!!!!
            //已上过的课程,只留集合最后两个数据
            List<wlx_schedule> lastTwoList = WLXGreenDaoUtil.getScheduleDao().queryBuilder().where
                    (wlx_scheduleDao.Properties
                            .Grade_id.eq(grade_id)).where(wlx_scheduleDao.Properties
                    .Closing_date.lt
                            (currentTimestamp)).orderAsc(wlx_scheduleDao.Properties.Opening_date)
                    .list();
            wlx_schedule lastOneSchedule = lastTwoList.get(lastTwoList.size() - 1);
            wlx_schedule lastTwoSchedule = lastTwoList.get(lastTwoList.size() - 2);
            scheduleList1 = new ArrayList();
            scheduleList1.add(0, lastOneSchedule);
            scheduleList1.add(0, lastTwoSchedule);
            //还未上过课的集合,将已上过课集合中的最后两个元素添加到未上课集合中
            scheduleList = WLXGreenDaoUtil.getScheduleDao().queryBuilder().where
                    (wlx_scheduleDao.Properties.Grade_id.eq(grade_id)).where(wlx_scheduleDao
                    .Properties.Closing_date.gt(currentTimestamp)).orderAsc(wlx_scheduleDao
                    .Properties.Opening_date).offset((paging_index - 1) *
                    paging_size).limit(paging_size).list();
            scheduleList1.addAll(scheduleList);
//            scheduleList.add(0, lastOneSchedule);
//            scheduleList.add(0, lastTwoSchedule);
            for (wlx_schedule wlx_schedule : scheduleList1) {
                WLXLogUtil.printE("课程内容:"+wlx_schedule.getPrepare_content());
            }
            //是否有更多数据
            mHasMoreData=scheduleList.size()!=0;
            if (paging_index == 1) {//下拉刷新,直接加载所有的未点评数据
                mRefreshLayout.endRefreshing();
                // TODO: 16/10/21  set全部学生集合scheduleAllList
                courseManageAdapter.setData(scheduleList1);
//                courseManageAdapter.setData(scheduleAllList);
                courseManageAdapter.notifyDataSetChanged();

                if (scheduleList1.size()==0&&scheduleList.size()==0) {
                    mRefreshLayout.setVisibility(View.GONE);
                    mRlContainerEmpty.setVisibility(View.VISIBLE);
//                    mTvMsg.setText("没有作业点评数据");
                    mTvMsg.setText("暂无数据");
                    return;
                }

            }else {
                mRefreshLayout.endLoadingMore();
                //上拉刷新,只需要刷新历史数据
                if (mHasMoreData) {
                    int count = courseManageAdapter.getCount();
                    // TODO: 16/10/21  set全部学生集合scheduleAllList
                    courseManageAdapter.addData(scheduleList1);
//                    courseManageAdapter.addData(scheduleAllList);
                    courseManageAdapter.notifyDataSetChanged();
                    courseManageListView.setSelection(count);
                } else {
                    WLXCustomToast.show("没有更多数据");
                }
            }
        }

    }}




